<template>
  <view class="home">
    <!-- 这里有了banner大图后需要替换掉 -->
    <view class="banner">
      <img
        mode="widthFix"
        src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-community/ysgc.png"
      />
    </view>
    <!-- <view class="box paddingBot0">登录或注册成为万户健康社区会员时，需获取您的手机号码。</view> -->
    <view class="footbox">
      <view class="agreeBox" @click="readArticle">
        为了保护您的合法权益，请您仔细阅读
        <span class="blue">《{{ title }}》</span>、<span class="blue">《{{ title_two }}》</span
        >，充分理解所有条款内容后点击“加入项目”。
      </view>
    </view>
    <!-- 如果有token，不需要再去授权了 -->
    <view v-if="!phoneBtnVisible && isInitPage" class="marginTop30">
      <fixed-bottom-button>
        <userProfileAuthorization
          v-if="canIUseGetUserProfile"
          @authorOk="authorOk"
          @authorClose="authorClose"
        ></userProfileAuthorization>
        <userInfoAuthorization v-else @authorOk="authorOk" @authorClose="authorClose"></userInfoAuthorization>
      </fixed-bottom-button>
    </view>
    <view v-else>
      <minPopUp :show="phoneVisiable && isInitPage" heightSize="460" @close="close">
        <view class="pupBox">
          <view class="phoneTitle">
            <img
              class="sqLogo"
              src="https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/sqlogo.png"
            />
            万户健康 申请</view
          >
          <view class="tips">注册或登录万户健康项目会员时，需获取您的手机号。</view>
          <view class="phoneRow">
            <button class="bt reject" @click="phoneVisiable = false">拒绝</button>
            <button
              class="bt"
              open-type="getPhoneNumber"
              withCredentials="true"
              @click="phoneVisiable = false"
              @getphonenumber="getPhoneNumber"
            >
              允许
            </button>
          </view>
        </view>
      </minPopUp>
      <!-- <view v-if="phoneVisiable && isInitPage" class="popBox">
        <view class="popBody">
          <view class="popCon">
            <view class="domCen">注册或登录万户健康项目会员时，需获取您的手机号。</view>
          </view>
          <view class="popFoot">
            <view class="buttonStyle">
              <button class="getPhoneBtn spans close" @click="phoneVisiable = false">不同意</button>
              <button
                class="getPhoneBtn spans"
                open-type="getPhoneNumber"
                withCredentials="true"
                @getphonenumber="getPhoneNumber"
              >
                同意
              </button>
            </view>
          </view>
        </view>
      </view> -->
      <!-- <button type="default" @click="getPhone">了解详情</button> -->
      <fixed-bottom-button>
        <view class="phonePop">
          <button
            class="getPhoneBtn"
            open-type="getPhoneNumber"
            withCredentials="true"
            @getphonenumber="getPhoneNumber"
          >
            微信授权
          </button>
        </view>
      </fixed-bottom-button>
    </view>

    <view v-if="agreeArticleShow">
      <agreeScroll :title="title" :content="content" :articleIndex="1" @popCenter="popCenter"></agreeScroll>
    </view>
    <view v-if="agreeArticleShow_two">
      <agreeScroll :title="title_two" :content="content_two" :articleIndex="2" @popCenter="popCenter"></agreeScroll>
    </view>
  </view>
</template>

<script>
import userInfoAuthorization from '@/components/userInfoAuthorization';
import userProfileAuthorization from '@/components/userProfileAuthorization';
import agreeScroll from '@/components/agreeScroll';
import { hospitalId, authorizeProxyArticleId, agreementArticleId, registerSource } from '@/common/baseUrl.js';
// 引入统计
import { tongji } from '@/utils/tools.js';
import fixedBottomButton from '@/components/fixedBottomBtn';
import minPopUp from '@/components/minPopup';
// 引入vux mapState
import { mapState } from 'vuex';
import {
  getAppid,
  login,
  sendPhone,
  getPatientIdByIdCard,
  getToken,
  bindPatients,
  getUserInfoByPatientId,
  getArticleDetails
} from '@/api/join.js';

export default {
  components: {
    userInfoAuthorization,
    userProfileAuthorization,
    agreeScroll,
    fixedBottomButton,
    minPopUp
  },
  data() {
    return {
      token: this.$store.getters.token,
      phoneBtnVisible: false,
      phoneVisiable: true,
      // banner: banner,
      authorizeProxyArticleId: authorizeProxyArticleId,
      agreementArticleId: agreementArticleId,
      agreeArticleShow: false,
      agreeArticleShow_two: false,
      title: '',
      content: '',
      title_two: '',
      content_two: '',
      artNumber: 1,
      isInitPage: false,
      canIUseGetUserProfile: false,
      show_pop: true
    };
  },
  computed: {
    ...mapState('join', {
      referers: 'referers'
    })
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.canIUseGetUserProfile = true;
    }
    // eslint-disable-next-line
    this.$store.commit('join/SET_RAWDATA', '');
    this.$store.commit('join/SET_SIGNATURE', '');
    this.$store.commit('join/SET_SESSIONKEY', '');
    this.getAppidObj();
    this.getArticle();
  },
  methods: {
    close() {
      this.show_pop = false;
    },
    // 打开事件
    showPop() {
      this.show_pop = true;
    },
    getAppidObj() {
      const self = this;
      uni.showToast({
        title: '加载中',
        icon: 'loading',
        duration: 15000,
        mask: true
      });
      getAppid('gyxm').then((coderes) => {
        this.$store.commit('join/SET_APPID', coderes.data || self.$store.getters.appid);
        wx.login({
          success: (res) => {
            console.log(res);
            if (res.code) {
              const data = {
                jscode: res.code,
                appid: coderes.data || self.$store.getters.appid
              };
              console.log('login data:', data);
              login(data).then((res) => {
                setTimeout(function () {
                  uni.hideToast();
                }, 600);
                if (res.code === 0) {
                  this.$store.commit('join/SET_SESSIONKEY', res.data.sessionKey);
                  this.$store.commit('join/SET_OPENID', res.data.openid);
                  this.$store.commit('join/SET_UNIONID', res.data.unionid);
                  this.isInitPage = true;
                  this.show_pop = true;
                } else {
                  uni.showToast({
                    title: res.message,
                    duration: 2000,
                    icon: 'none'
                  });
                }
              });
            } else {
              uni.showToast({
                title: res.errMsg,
                duration: 2000,
                icon: 'none'
              });
              console.log('登录失败！' + res.errMsg);
            }
          }
        });
      });
    },
    async getPhoneNumber(e) {
      tongji('c4e6086a-6d50-4948-b543-6db49394f3c0');
      const self = this;
      uni.showToast({
        title: '加载中',
        icon: 'loading',
        duration: 15000,
        mask: true
      });
      this.phoneVisiable = false;
      console.log(123123, this.phoneVisiable);
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        const data = {
          appid: this.$store.getters.appid || this.$store.getters.spareappid,
          sessionKey: this.$store.getters.sessionKey,
          signature: this.$store.getters.signature,
          rawData: this.$store.getters.rawData,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        };
        console.log('data:', data);
        console.log('微信用户信息', this.$store.getters.rawData);
        let userJsonInfo = null;
        if (this.$store.getters.rawData) {
          userJsonInfo = JSON.parse(this.$store.getters.rawData);
          console.log(userJsonInfo);
        }
        // 给后台发送手机号相关微信数据
        await sendPhone(data).then((phoneres) => {
          if (phoneres.code === 0) {
            this.$store.commit('join/SET_PHONE', phoneres.data.phoneNumber);
            // 通过unionid获取用户patientid
            const ownData = {
              phone: self.$store.getters.phone,
              idCard: ''
            };
            getPatientIdByIdCard(ownData).then((patientidres) => {
              // 老用户直接登录，获取token
              if (patientidres.code === 0 && patientidres.data) {
                self.getTokenObj(patientidres.data);
                // 新用户先去签约，拿到patientid，然后获取token
              } else if (patientidres.code === 0 && !patientidres.data) {
                const bindPatientInfo = {
                  phone: self.$store.getters.phone,
                  name: userJsonInfo && userJsonInfo.nickName ? userJsonInfo.nickName : self.$store.getters.phone,
                  hospitalId: hospitalId,
                  source: registerSource,
                  cid: uni.getStorageSync('cid') || ''
                };
                bindPatients(bindPatientInfo).then((bindPatientsRes) => {
                  if (bindPatientsRes.code === 0 && bindPatientsRes.data) {
                    self.getTokenObj(bindPatientsRes.data);
                  } else {
                    uni.showToast({
                      title: bindPatientsRes.message,
                      duration: 2000,
                      icon: 'none'
                    });
                  }
                });
              } else {
                uni.showToast({
                  title: patientidres.message,
                  duration: 2000,
                  icon: 'none'
                });
              }
            });
          } else {
            uni.showToast({
              title: phoneres.message,
              duration: 2000,
              icon: 'none'
            });
          }
        });
      } else {
        uni.showToast('拒绝');
        console.log('用户点击了拒绝', e);
      }

      // 友盟数据埋点
      tongji('18863eef-d468-4d7f-a681-a8c2e56eed34');
    },
    getTokenObj(patientId) {
      const self = this;
      self.$store.commit('join/SET_PATIENTID', patientId);
      const tokenData = {
        appid: self.$store.getters.appid,
        unionId: self.$store.getters.unionid,
        openId: self.$store.getters.openid,
        patientId: patientId
      };
      // 通过patientid获取token
      getToken(tokenData).then((tokenres) => {
        setTimeout(function () {
          uni.hideToast();
        }, 600);
        if (tokenres.code === 0 && tokenres.data) {
          self.$store.commit('join/SET_TOKEN', tokenres.data);
          // self.isAuthorName(patientId);
          this.jumpPage();
          // this.$wxPromise.navigateTo({
          //   url: '/pages/index/index'
          // });
        }
      });
    },
    isAuthorName(patientId) {
      getUserInfoByPatientId(patientId).then((res) => {
        if (res.code === 0 && res.data.realNameAuthenticationPassed === 1) {
          this.jumpPage();
          // this.$wxPromise.navigateTo({
          //   url: '/pages/index/index'
          // });
        } else {
          this.jumpPage();
          // this.$wxPromise.navigateTo({
          //   url: '/pages/join/authorIdentityChaeck'
          // });
        }
      });
    },
    authorOk() {
      console.log('authorOk');
      this.show_pop = true;
      this.phoneBtnVisible = true;
      tongji('2f653ea6-068d-491d-99e3-f1d953120b98');
    },
    authorClose() {
      console.log('取消授权1');
    },
    async getArticle() {
      getArticleDetails(authorizeProxyArticleId).then((res) => {
        if (res.code === 0) {
          this.title = res.data.title;
          this.content = res.data.content;
        } else {
          uni.showToast({ title: res.message, icon: 'none' });
        }
      });
      getArticleDetails(agreementArticleId).then((res) => {
        if (res.code === 0) {
          this.title_two = res.data.title;
          this.content_two = res.data.content;
        } else {
          uni.showToast({ title: res.message, icon: 'none' });
        }
      });
    },
    async readArticle() {
      this.agreeArticleShow = true;
    },
    async popCenter(val) {
      this.agreeArticleShow = false;
      this.agreeArticleShow_two = false;
      if (val === 1) {
        this.agreeArticleShow_two = true;
      }
    },
    jumpPage() {
      // eslint-disable-next-line no-undef
      const pages = getCurrentPages(); // 当前页
      const beforePage = pages && pages.length > 1 ? pages[pages.length - 2] : false; // 上个页面
      // 有指定路劲，按指定路劲。没有查找有没有历史，有返回上级，什么都没有直接去首页
      let beforePagePath = beforePage.route;
      let options = beforePage.options;
      let keys = Object.keys(options);
      if (keys.length > 0) {
        let query = '';
        keys.forEach((key) => {
          query += key + '=' + options[key];
        });
        beforePagePath += '?' + query;
      }
      console.log('jumpPage beforePagePath:', beforePagePath);
      if (beforePagePath) {
        this.$wxPromise.reLaunch({
          url: '/' + beforePagePath
        });
      } else {
        this.$wxPromise.reLaunch({
          url: '/pages/index/index'
        });
      }
    }
  }
};
</script>
<style>
page {
  background-color: #fff;
}
.uni-btn-v button {
  border: none !important;
}
button:after {
  border: none !important;
}
</style>
<style scoped>
.banner {
  text-align: center;
  padding: 0 70rpx;
  padding-top: 72rpx;
}
.box {
  padding: 20px;
}
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}
.getPhoneBtn {
  color: #fff;
  width: 700rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 36rpx;
  background: -moz-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fe894d), color-stop(100%, #ef3931));
  background: -webkit-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: -o-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: -ms-linear-gradient(top, #fe894d 0%, #ef3931 100%);
  background: linear-gradient(to bottom, #fe894d 0%, #ef3931 100%);
}
.buttonStyle {
  text-align: center;
}
.buttonStyle .getPhoneBtn {
  display: inline-block;
  width: 35%;
  margin: 4%;
  border-radius: 14rpx;
  height: 78rpx;
  line-height: 78rpx;
  font-size: 28rpx;
}
.buttonStyle .close {
  background: none;
  background-color: #fff;
  color: #333;
}
.banner {
  text-align: center;
}
.banner img {
  width: 100%;
}
.margin20 {
  margin: 40rpx;
}
.marginTop30 {
  margin-top: 20rpx;
}
</style>
<style lang="scss">
.home {
  padding-bottom: 152rpx;
}
.popBox {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  z-index: 9;
  .popBody {
    background-color: #fff;
    border-radius: 24rpx;
    width: 650rpx;
    height: auto;
    margin: 0 auto;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 9;
    overflow: hidden;
    .head {
      padding: 24rpx;
      text-align: center;
      background-color: #f3f3f3;
      font-size: 32rpx;
    }
    .popCon {
      padding: 24rpx;
      font-size: 28rpx;
      .domCen {
        text-align: center;
        padding: 40rpx 24rpx;
        padding-bottom: 0;
        font-size: 28rpx;
      }
    }
    .popFoot {
      .close {
        background-color: #f3f3f3;
      }
      .center {
        background-color: #f34e1c;
        color: #fff;
      }
    }
  }
}
.footbox {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 40rpx;
  padding-top: 0;
  color: #666;
}
.blue {
  color: #418dc7;
}

.fixBottom {
  position: fixed;
  bottom: 68rpx;
  left: 50%;
  transform: translateX(-50%);
}
.paddingBot0 {
  padding-bottom: 0 !important;
}
.pupBox {
  padding: 30rpx;
  padding-top: 60rpx;
  border-radius: 10rpx;
  overflow: hidden;
  .phoneTitle {
    font-size: 28rpx;
    color: #000;
    position: relative;
    padding-left: 60rpx;
    .sqLogo {
      position: absolute;
      left: 0;
      top: -6rpx;
      width: 50rpx;
      height: 50rpx;
      border-radius: 100%;
    }
  }
  .tips {
    color: #000;
    font-size: 34rpx;
    margin: 38rpx 0;
    border-bottom: 2rpx solid rgba(232, 232, 232, 1);
    padding-bottom: 40rpx;
    margin-bottom: 220rpx;
    // font-weight: bold;
  }
}
.phoneRow {
  text-align: center;
  .bt {
    display: inline-block;
    background-color: rgba(7, 193, 96, 1);
    color: #fff;
    width: 200rpx;
    text-align: center;
    margin: 16rpx;
    font-size: 28rpx;
    border: 2rpx solid rgba(7, 193, 96, 1);
    border-radius: 8rpx;
  }
  .reject {
    background-color: rgba(0, 0, 0, 0.05);
    color: rgba(7, 193, 96, 1);
    border: 2rpx solid #f3f3f3;
  }
}
</style>
